<template>
  <div id="UserManagePage">
    <a-form :model="searchParams" layout="inline" @finish="doSearch" style="padding-bottom: 20px">
      <a-form-item label="名称">
        <a-input v-model:value="searchParams.book_name" placeholder="请输入图书名称" allow-clear />
      </a-form-item>
      <a-form-item label="ISBN编号">
        <a-input v-model:value="searchParams.book_isbn" placeholder="请输入ISBN编号" allow-clear />
      </a-form-item>
      <a-form-item label="分类">
        <a-select
          v-model:value="searchParams.book_category"
          placeholder="请选择分类"
          allowClear
          style="width: 197px"
        >
          <a-select-option
            v-for="item in categoryOptions"
            :key="item"
            :value="item.value"
            placeholder="请选择分类"
            >{{ item.label }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-button type="primary" htmlType="submit">搜索</a-button>
      <div class="addBook">
        <a-button type="primary" @click="showDrawer" style="margin-left: 20px">添加图书</a-button>
        <a-drawer
          :width="500"
          :title="editBookId ? '编辑图书' : '添加图书'"
          placement="right"
          :open="open"
          @close="onClose"
        >
          <template #extra>
            <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
            <a-button type="primary" @click="doSumbit">{{
              editBookId ? '保存修改' : '新增'
            }}</a-button>
          </template>
          <a-form
            :model="bookForm"
            name="addBookForm"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
            autocomplete="off"
            ref="bookFormRef"
          >
            <!-- 图书名称 -->
            <a-form-item
              label="图书名称"
              name="book_name"
              :rules="[{ required: true, message: '请输入图书名称!' }]"
            >
              <a-input v-model:value="bookForm.book_name" placeholder="请输入图书名称" />
            </a-form-item>
            <!-- 图书分类 -->
            <a-form-item
              label="图书分类"
              name="book_category"
              :rules="[{ required: true, message: '请选择图书分类!' }]"
            >
              <a-select v-model:value="bookForm.book_category" placeholder="请输入分类" allowClear>
                <a-select-option v-for="item in categoryOptions" :key="item" :value="item.value">{{
                  item.label
                }}</a-select-option>
              </a-select>
            </a-form-item>

            <!-- ISBN编号 -->
            <a-form-item
              label="ISBN编号"
              name="book_isbn"
              :rules="[{ required: true, message: '请输入ISBN编号!' }]"
            >
              <a-input v-model:value="bookForm.book_isbn" placeholder="请输入ISBN编号" />
            </a-form-item>

            <!-- 图书作者 -->
            <a-form-item
              label="图书作者"
              name="book_author"
              :rules="[{ required: true, message: '请输入图书作者!' }]"
            >
              <a-input v-model:value="bookForm.book_author" placeholder="请输入图书作者" />
            </a-form-item>

            <!-- 图书出版社 -->
            <a-form-item
              label="出版社"
              name="book_press"
              :rules="[{ required: true, message: '请输入出版社名称!' }]"
            >
              <a-input v-model:value="bookForm.book_press" placeholder="请输入出版社名称" />
            </a-form-item>

            <!-- 图书价格 -->
            <a-form-item
              label="图书价格"
              name="book_price"
              :rules="[
                { required: true, message: '请输入图书价格!' },
                { type: 'number', min: 0, message: '价格必须大于等于0' },
              ]"
            >
              <a-input-number
                v-model:value="bookForm.book_price"
                placeholder="请输入图书价格"
                style="width: 100%"
                :formatter="(value) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="(value) => value.replace(/\￥\s?|(,*)/g, '')"
              />
            </a-form-item>

            <!-- 图书页数 -->
            <a-form-item
              label="图书页数"
              name="book_pagination"
              :rules="[{ required: true, message: '请输入图书页数!' }]"
            >
              <a-input-number
                v-model:value="bookForm.book_pagination"
                placeholder="请输入图书页数"
                style="width: 100%"
              />
            </a-form-item>

            <!-- 图书状态 -->
            <a-form-item
              label="图书状态"
              name="book_status"
              :rules="[{ required: true, message: '请选择图书状态!' }]"
            >
              <a-select v-model:value="bookForm.book_status" placeholder="请选择图书状态">
                <a-select-option value="0">可借阅</a-select-option>
                <a-select-option value="1">不可借阅</a-select-option>
              </a-select>
            </a-form-item>

            <!-- 上架时间 -->
            <a-form-item
              label="上架时间"
              name="book_uploadtime"
              :rules="[{ required: true, message: '请选择上架时间!' }]"
            >
              <a-date-picker
                v-model:value="bookForm.book_uploadtime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择上架时间"
                style="width: 100%"
              />
            </a-form-item>

            <!-- 图书封面 -->
            <a-form-item label="图书封面" name="book_url">
              <PictureUpload :picture="picture" :onSuccess="onSuccess" />
              <p class="ant-upload-hint" style="margin-top: 8px">支持JPG、PNG格式，建议尺寸1:1.5</p>
            </a-form-item>
          </a-form>
        </a-drawer>
      </div>
    </a-form>
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
      :loading="loading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'book_url'">
          <a-image :src="record.book_url" :width="100" :height="100" />
        </template>
        <template v-if="column.dataIndex === 'book_price'">
          <span style="color: red"> ￥{{ record.book_price }} </span>
        </template>
        <template v-else-if="column.dataIndex === 'book_status'">
          <div class="book_status">
            <div v-if="record.book_status === '0'">
              <a-tag color="green">可借阅</a-tag>
            </div>
            <div v-else>
              <a-tag color="red">不可借阅</a-tag>
            </div>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'book_uploadtime'">
          <span>{{ dayjs(record.book_uploadtime).format('YYYY-MM-DD HH:mm:ss') }}</span>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-popconfirm
            title="确定要删除图书吗？"
            @confirm="() => doDelete(record.book_id)"
            okText="确定"
            cancelText="取消"
          >
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
          <!-- <router-link :to="{ path: '/admin/book/edit', query: { book_id: record.book_id } }"> -->
          <a-button type="link" style="margin-left: 20px" @click="showDrawer(record)"
            >编辑</a-button
          >
          <!-- </router-link> -->
        </template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import {
  addBookUsingPost,
  deleteBookUsingPost,
  getTagCategoryUsingGet,
  listBookByPageUsingPost,
  updateBookUsingPost,
} from '@/api/bookController'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { computed, onMounted, reactive, ref } from 'vue'
import PictureUpload from '../book/BookPictureUpload.vue'
const open = ref<boolean>(false)
const categoryOptions = ref<string[]>([])
const editBookId = ref<API.BookVO>()

//列名称
const columns = [
  {
    title: 'id',
    dataIndex: 'book_id',
    width: 80,
  },
  {
    title: '封面',
    dataIndex: 'book_url',
  },
  {
    title: '名称',
    dataIndex: 'book_name',
  },
  {
    title: '分类',
    dataIndex: 'book_category',
    width: 100,
  },
  {
    title: 'ISBN编号',
    dataIndex: 'book_isbn',
  },
  {
    title: '图书出版社',
    dataIndex: 'book_press',
  },
  {
    title: '图书作者',
    dataIndex: 'book_author',
  },
  {
    title: '图书上架时间',
    dataIndex: 'book_uploadtime',
  },
  {
    title: '图书页数',
    dataIndex: 'book_pagination',
  },
  {
    title: '图书状态',
    dataIndex: 'book_status',
  },
  {
    title: '图书价格',
    dataIndex: 'book_price',
  },
  {
    title: '操作',
    key: 'action',
  },
]

const dataList = ref([])
const total = ref()

const loading = ref(false)
//添加图书
const bookForm = reactive<API.BookAddRequest>({
  book_name: '',
  book_category: '',
  book_isbn: '',
  book_press: '',
  book_author: '',
  book_pagination: 0,
  book_price: 0,
  book_url: '',
})
//搜索条件
const searchParams = reactive<API.BookQueryRequest>({
  current: 1,
  pageSize: 10,
})

//获取图书分类
const getCategoryList = async () => {
  const res = await getTagCategoryUsingGet()
  console.log('获取图书分类', res)
  if (res.data.data && res.data.code === 0) {
    categoryOptions.value = (res.data.data.book_category ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
  }
}

//分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

const showDrawer = (record?: API.BookVO) => {
  if (record) {
    editBookId.value = record.book_id
    Object.assign(bookForm, {
      ...record,
      book_uploadtime: dayjs(record.book_uploadtime),
    })
    picture.value = record.book_url ? { url: record.book_url } : null
  } else {
    editBookId.value = undefined
    resetForm()
  }
  open.value = true
}
// 重置表单函数
const resetForm = () => {
  Object.assign(bookForm, {
    book_name: '',
    book_category: undefined,
    book_isbn: '',
    book_press: '',
    book_author: '',
    book_pagination: undefined,
    book_price: undefined,
    book_url: '',
    book_status: undefined,
    book_uploadtime: undefined,
  })
  picture.value = null
}
const onClose = () => {
  open.value = false
}

const picture = ref()
const onSuccess = (newPicture: any) => {
  picture.value = newPicture
  bookForm.book_url = newPicture.url
  console.log('获取到图片的url', newPicture.url)
}
//获取图书列表
const getUserList = async () => {
  loading.value = true
  const res = await listBookByPageUsingPost(searchParams)
  console.log('获取图书列表', res)
  if (res.data.data && res.data.code === 0) {
    dataList.value = res.data.data.records
    total.value = res.data.data.total
  }
  loading.value = false
}

//切换表格页数
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  getUserList()
}
//删除图书
const doDelete = async (id: number) => {
  const res = await deleteBookUsingPost({ id })
  console.log('删除图书', res)
  if (res.data.code === 0 && res.data.data) {
    getUserList()
  }
}
//搜索
const doSearch = () => {
  searchParams.current = 1
  console.log('搜索', searchParams)
  getUserList()
}

//添加图书
const doSumbit = async () => {
  if (editBookId.value) {
    const res = await updateBookUsingPost({
      ...bookForm,
      book_id: editBookId.value,
    })
    console.log('修改图书', res)
    if (res.data.code === 0 && res.data.data) {
      message.success('修改成功')
      getUserList()
      onClose()
    }
  } else {
    const res = await addBookUsingPost(bookForm)
    console.log('添加图书', res)
    if (res.data.code === 0 && res.data.data) {
      message.success('添加成功')
      getUserList()
      onClose()
    }
  }
}
onMounted(() => {
  getUserList()
  getCategoryList()
})
</script>

<style lang="scss" scoped></style>
